from rest_framework import serializers

from goods.models import Goods


class CartSerializer(serializers.Serializer):
    """购物车序列化器类"""
    goods_id = serializers.IntegerField(label='商品ID')
    count = serializers.IntegerField(label='添加数量')
    selected = serializers.BooleanField(label='勾选状态', default=True)

    # 校验数据   校验商品id值和数量count，勾选状态并未校验
    def validate(self, attrs):
        # 检验goods_id 是否存在
        goods_id = attrs['goods_id']

        try:
            one_goods = Goods.objects.get(id=goods_id)
        except Goods.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        # 如果商品存在 检测用户所选数量是否超过最大库存量
        count = attrs['count']
        if count > one_goods.stock:
            raise serializers.ValidationError('商品库存不足')

        return attrs


class CartSKUSerializer(serializers.ModelSerializer):
    """购物车商品序列化器类"""
    count = serializers.IntegerField(label='数量')
    selected = serializers.BooleanField(label='是否勾选')

    class Meta:
        model = Goods
        fields = ('id', 'count', 'title', 'img_url', 'sell_price', 'selected')


class CartDelSerializer(serializers.Serializer):
    """购物车删除的序列化器类"""
    goods_id = serializers.IntegerField(label='商品id')

    def validate_goods_id(self, value):
        try:
            goods = Goods.objects.get(id=value)
        except Goods.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        return value

#
# class CartSelectSerializer(serializers.Serializer):
#     """购物车全选序列化器类"""
#     selected = serializers.BooleanField(label='是否全选')
